package com.sz.test.filter;

import com.alibaba.fastjson.JSON;
import com.sz.test.common.R;
import com.sz.test.context.SecurityContext;
import com.sz.test.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebFilter("*.action")
public class ApplicationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        request.setCharacterEncoding("UTF-8");
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("application/json;charset=utf-8");
        if (request.getRequestURI().equals("/api/login.action")) {
            filterChain.doFilter(request, response);
        }
        if (checkAuth(request, response)) {
            filterChain.doFilter(request, response);
        }
    }


    // 鉴权方法
    private boolean checkAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer methodRole = SecurityContext.getMethodRequireRoleAndPerms().get(request.getMethod()+"-"+request.getRequestURI());
        if (methodRole == null) {
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(R.error("未登录")));
            writer.close();
            return false;
        }
        String token = request.getHeader("token");
        Map<String, User> tokenMap = SecurityContext.getTokenMap();
        if (!tokenMap.containsKey(token)) {
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(R.error("未登录")));
            writer.close();
            return false;
        }
        User user = tokenMap.get(token);

        if (user.getRole() < methodRole) {
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(R.error("权限不够，不允许访问")));
            writer.close();
            return false;
        }
        System.out.println("鉴权通过，正常访问");
        return true;
    }


    @Override
    public void destroy() {
    }
}
